package com.wushi.lenovo.asia5b.app_push;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;

import com.bumptech.glide.Glide;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.mvp.base.BaseApplication;
import com.mvp.dagger.modules.NetworkModule;
import com.mvp.utils.AppUtil;
import com.mvp.utils.JsonUtil;
import com.mvp.utils.ResString;
import com.mvp.utils.SharedPreferencesUtils;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_model.other.PushBean;
import com.wushi.lenovo.asia5b.app_ui.other.activity.MainActivity;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/12/18.
 */
public class MyFirebaseMessagingService extends FirebaseMessagingService {
    public static PushBean bean = null;
    public static Bitmap bigBitmap = null;
    public static Bitmap smallBitmap = null;

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        d("--->>>>>>>>---" + "From: " + remoteMessage.getFrom());
        PushBean bean = null;
        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            d("--->>>>>>>>---收到firebase消息:");
            try {
                String json = JsonUtil.INSTANCE.anyToJson(remoteMessage.getData());
                NetworkModule.printJson(json);
                bean = JsonUtil.INSTANCE.jsonToAny(json, PushBean.class);
                if (false) {
                    notificationByBean(bean);
                } else {
                    NotificationHelper.receive(bean);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (true) {
            return;
        }

        RemoteMessage.Notification notification = null;
        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            d("--->>>>>>>>---" + "Message Notification Body: " + remoteMessage.getNotification().getBody());
            notification = remoteMessage.getNotification();

        }

    }

    public static void notificationByBean(PushBean bean) {
        Bitmap[] bitmaps = new Bitmap[2];//0:smallBitmap 1:bigBitmap
        if (!TextUtils.isEmpty(bean.getTitle()) && !TextUtils.isEmpty(bean.getBody())) {
            if (!TextUtils.isEmpty(bean.getSmallImageUrl()) || !TextUtils.isEmpty(bean.getBigImageUrl())) {
                Observable.just(bean)
                        .map(new Function<PushBean, PushBean>() {
                            @Override
                            public PushBean apply(PushBean pushBean) throws Exception {
                                String smallImgUrl = bean.getSmallImageUrl();
                                if (!TextUtils.isEmpty(smallImgUrl)) {
                                    bitmaps[0] = Glide.with(BaseApplication.sContext).asBitmap().load(smallImgUrl).submit().get();
                                }
                                String bigImgUrl = bean.getSmallImageUrl();
                                if (!TextUtils.isEmpty(bigImgUrl)) {
                                    bitmaps[1] = Glide.with(BaseApplication.sContext).asBitmap().load(bigImgUrl).submit().get();
                                }
                                return pushBean;
                            }
                        })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(result -> {
                            sendNotification(bean, bitmaps[0], bitmaps[1]);
                        }, throwable -> {
                            throwable.printStackTrace();
                            sendNotification(bean, null, null);
                        });
            } else {
                sendNotification(bean, null, null);
            }
        }
    }

    /**
     * 自定义通知样式
     *
     * @param bean
     * @param action      small/big  此时此刻展示小视图/大视图
     * @param smallBitmap
     * @param bigBitmap
     */
    public static void sendSmallAndBigNotification(PushBean bean, String action, Bitmap smallBitmap, Bitmap bigBitmap) {
        //避免使用序列化
        MyFirebaseMessagingService.bean = bean;
        MyFirebaseMessagingService.smallBitmap = smallBitmap;
        MyFirebaseMessagingService.bigBitmap = bigBitmap;

        Context context = BaseApplication.sContext;

        //视图点击
        Intent intent = new Intent(context, MainActivity.class);
        if (bean != null) {
            intent.putExtra(FireBasePushHelper.channel_data, FireBasePushHelper.channel_data_value);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = ResString.get(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder;
        RemoteViews remoteViews;
        if (TextUtils.equals(action, "small")) {
            Intent intentToBig = new Intent(BaseApplication.sContext, PushBroadCast.class);
            intentToBig.setAction("big");
            PendingIntent broadcastToBig = PendingIntent.getBroadcast(BaseApplication.sContext, 12, intentToBig, PendingIntent.FLAG_ONE_SHOT);
            remoteViews = new RemoteViews(AppUtil.INSTANCE.getPackageName(), R.layout.view_notify);
            remoteViews.setTextViewText(R.id.tv_notify_title, bean.getTitle());
            remoteViews.setTextViewText(R.id.tv_notify_content, bean.getBody());
            if (smallBitmap != null) {
                remoteViews.setImageViewBitmap(R.id.iv_notify_smallimg, smallBitmap);
                remoteViews.setViewVisibility(R.id.iv_notify_smallimg, View.VISIBLE);
            }
            if (bigBitmap != null) {//如果有大图,视图点击后变大
                remoteViews.setOnClickPendingIntent(R.id.ll_notify_icon_vessel, broadcastToBig);
            }
            notificationBuilder =
                    new NotificationCompat.Builder(context, channelId)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setCustomContentView(remoteViews)
                            .setWhen(System.currentTimeMillis())
                            .setAutoCancel(true)
                            .setSound(defaultSoundUri)
                            .setContentIntent(pendingIntent);
        } else {
            Intent intentToSmall = new Intent(BaseApplication.sContext, PushBroadCast.class);
            intentToSmall.setAction("small");
            PendingIntent broadcastToSmall = PendingIntent.getBroadcast(BaseApplication.sContext, 12, intentToSmall, PendingIntent.FLAG_ONE_SHOT);
            remoteViews = new RemoteViews(AppUtil.INSTANCE.getPackageName(), R.layout.view_notify);
            remoteViews.setTextViewText(R.id.tv_notify_title, bean.getTitle());
            remoteViews.setTextViewText(R.id.tv_notify_content, bean.getBody());
            if (bigBitmap != null) {
                remoteViews.setImageViewBitmap(R.id.iv_notify_bigimg, bigBitmap);
                remoteViews.setViewVisibility(R.id.iv_notify_bigimg, View.VISIBLE);
            }
            //如果有小图,视图点击后变小
            remoteViews.setOnClickPendingIntent(R.id.ll_notify_icon_vessel, broadcastToSmall);
            notificationBuilder =
                    new NotificationCompat.Builder(context, channelId)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setCustomBigContentView(remoteViews)
                            .setWhen(System.currentTimeMillis())
                            .setAutoCancel(true)
                            .setSound(defaultSoundUri)
                            .setContentIntent(pendingIntent);
        }

        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Asia5B message",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }
        Notification notification = notificationBuilder.build();
        notificationManager.notify(bean.getNotifyId() /* ID of notification */, notification);
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     */
    @SuppressLint("RestrictedApi")
    private static void sendNotification(PushBean bean, Bitmap smallBitmap, Bitmap bigBitmap) {
        boolean isNofity = false;//是否已经推送了
        String notifyJson = (String) SharedPreferencesUtils.getData("notify", "");
        isNofity = notifyJson.contains("" + bean.getNotifyId());
        if (isNofity && false) {
            return;
        } else {
            SharedPreferencesUtils.putData("notify", notifyJson + "," + bean.getNotifyId());
        }
        if (false) {//是否使用自定义通知样式
            sendSmallAndBigNotification(bean, "small", smallBitmap, bigBitmap);
            return;
        }
        //避免使用序列化
        MyFirebaseMessagingService.bean = bean;

        //视图点击
        Intent intent = new Intent(BaseApplication.sContext, MainActivity.class);
        if (bean != null) {
            intent.putExtra(FireBasePushHelper.channel_data, FireBasePushHelper.channel_data_value);
        }
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//todo 不需要重启应用,还没测试过
        PendingIntent pendingIntent = PendingIntent.getActivity(BaseApplication.sContext, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);
        String channelId = ResString.get(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        smallBitmap = BitmapFactory.decodeResource(BaseApplication.sContext.getResources(), R.mipmap.ic_launcher);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(BaseApplication.sContext, channelId)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(smallBitmap)
                        .setStyle(bigBitmap == null ? null : new NotificationCompat.BigPictureStyle()
                                .bigPicture(bigBitmap)
                                .bigLargeIcon(smallBitmap))
                        .setContentTitle(bean.getTitle())
                        .setContentText(bean.getBody())
                        .setWhen(System.currentTimeMillis())
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) BaseApplication.sContext.getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Asia5B message",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }
        Notification notification = notificationBuilder.build();
        notificationManager.notify(bean.getNotifyId() /* ID of notification */, notification);
        d("--->>>>>>>>---推送消息显示完毕");
    }


}
